<template>
  <div>
    <div class="model-title">
      <img src="@/assets/images/tripartite/icon_title.png">
      <span>集约化建设检测</span>
    </div>
    <div>
      <el-tabs>
        <el-tab-pane v-for="item in data" :key="item.lotDeviceId" :label="item.productName" :name="item.iotDeviceId">
          <div class="jy-box">
            <div class="descriptions">
              <el-descriptions border :column="1" contentClassName="descriptions-content">
                <el-descriptions-item label="申请数量">{{ item.deviceNum }}</el-descriptions-item>
                <el-descriptions-item label="重复数量">{{ getData(item.lotDeviceId) }}</el-descriptions-item>
                <el-descriptions-item label="建设地点">{{ item.constructionSite }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <div class="jybox-left">
              <div class="jybox-title">重复比例</div>
              <el-progress type="circle" :width="80"
                :percentage="parseInt(Math.min(getData(item.lotDeviceId) * 100 / item.deviceNum, 100)) || 0"
                :stroke-width="10" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="model-title">
      <img src="@/assets/images/tripartite/icon_title.png">
      <span>设备地图</span>
    </div>
    <div>
      <ul>
        <li class="label" v-for="(item, $index) in data" :key="item.lotDeviceId" @click="togglePopup(item, $index)">
          <span class="color-icon" :style="{ background: getColor($index) }"></span>{{ item.productName }}</li>
      </ul>
    </div>
    <div id="draw-map" class="draw-map"></div>
    <div>
      <div class="model-title">
        <img src="@/assets/images/tripartite/icon_title.png">
        <span>重复设备明细 - <span v-if="currentData"><span class="color-icon"
              :style="{ background: currentData.color }"></span>{{ currentData ? currentData.productName : '无'
              }}</span><span v-else>点击设备颜色标签查询</span></span>
      </div>
      <el-table :data="repetitionIotDeviceInfo" border class="table_technical">
        <el-table-column label="序号" align="center" type="index" width="65" />
        <el-table-column prop="PRODUCT_NAME" label="产品名称" align="center" :show-overflow-tooltip="true" />
        <el-table-column prop="NAME" label="设备名称" align="center" :show-overflow-tooltip="true" />
        <el-table-column prop="DEVICE_APPLICATION_NAME" label="所属项目" align="center" :show-overflow-tooltip="true" />
        <el-table-column prop="DEPARTMENT_NAME" label="所属部门" align="center" :show-overflow-tooltip="true" />
        <el-table-column prop="ADDRESS" label="设置位置" align="center" :show-overflow-tooltip="true" />
        <el-table-column prop="CREATETIME" label="建设时间" align="center" :show-overflow-tooltip="true" />
        <el-table-column prop="DEVICE_STATUS" label="状态" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.DEVICE_STATUS !== '1.0' ? '在线' : '离线' }}
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-show="total > 0" background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :page-size="queryParams.pageSize" :current-page="queryParams.pageNum" :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" class="pagination">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import LeafletMap from '@/utils/map';
import { getColor } from '@/utils/constant';
const ORANGE_COLOR = '#df822d';
const BLUE_COLOR = '#3171ee';
const DIV_ICON = L.divIcon({
  html: "<div class='smallCircleMarker' style='background-color: red;'></div>",
  className: 'ss',
  iconAnchor: [7, 7]
});
function getInfowindow(data) {
  return `
    <div class="info-card">
    <div class="info--title">
      <p>${data.productName}</p>
    </div>
    <div class="info--content">
      <p>同类型设备: ${data.totalCount}</p>
      <p>建设地点: ${data.constructionSite}</p>
      <p>建设方式: ${data.constructionWay}</p>
      <p>半径: ${data.radius.toFixed(2)}米</p>
    </div>

  </div>
    `;
}
export default {
  name: 'Draw',
  props: {
    data: Array
  },
  data() {
    return {
      map: null,
      plottingLayer: null,
      drawControl: null,
      editableLayers: null,
      currentLayer: null,
      circles: [],
      polygons: [],
      queryParams: {
        pageSize: 10,
        pageNum: 1
      },
      total: 0,
      repetitionIotDeviceInfo: [],
      currentData: null,
      dataMap: []
    }
  },
  mounted() {
    setTimeout(() => {
      LeafletMap.init({
        elId: 'draw-map',
        search: false,
        ready: (map) => {
          this.map = map
          // this.initDraw()
          this.data.forEach((item, index) => {
            this.queryCircle({ ...item, color: this.getColor(index) })
          })
          // this.queryService()
        }
      })
    }, 2000)
  },
  watch: {
    data(newVal) {
    }
  },
  methods: {
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize;
      this.getRepetitionIotDeviceInfo(this.currentData)
    },
    handleCurrentChange(pageNum) {
      this.queryParams.pageNum = pageNum;
      this.getRepetitionIotDeviceInfo(this.currentData)
    },
    initDraw() {
      let map = this.map;
      var editableLayers = new L.FeatureGroup();
      map.addLayer(editableLayers);

      let drawControl = new L.Control.Draw({
        edit: {
          featureGroup: editableLayers,
          poly: {
            allowIntersection: false
          }
        },
        draw: {
          polygon: false,
          rectangle: false,
          circle: {
            radius: 10000
          },
          marker: false,
          polyline: false,
          circlemarker: false,
        },

      });
      map.addControl(drawControl);

      map.on(L.Draw.Event.CREATED, (e) => {
        var type = e.layerType,
          layer = e.layer;

        if (type === 'marker') {
          layer.bindPopup('A popup!');
        }
        layer.type = type
        if (editableLayers.getLayers().length > 0) return this.$message.warning('只允许绘制一个位置');
        editableLayers.addLayer(layer);
      });
      this.drawControl = drawControl
      this.editableLayers = editableLayers
    },
    drawCircle(lat, lng, radius = 2000, color = '#df822d', name) {
      let center = L.latLng([lat, lng]);
      let circle = new L.Circle(center, radius, {
        color
      })
      circle.name = name
      circle.tag = this.getTag(lat, lng, name)

      this.map.addLayer(circle)
      this.circles.push(circle)
      return circle
    },
    getTag(lat, lng, name) {
      return `${name}${lat}${lng}`;
    },
    editCircle() {
      this.drawControl.fire('edit')
    },
    getLayerData(layer) {
      if (layer.type === 'circle') {
        const result = {
          latlng: layer.getLatLng(),
          radius: layer.getRadius()
        }
        this.queryCircle(result.latlng, result.radius)
        return result;
      }
    },
    queryCircle(data) {
      const { latitude, longitude, radius, deviceType, color, productName } = data;
      const lat = latitude;
      const lng = longitude;
      if (!deviceType) {
        let circle = this.drawCircle(lat, lng, radius, color, data.productName);
        circle.bindCustomPopup(getInfowindow({ ...data, totalCount: '-' }))
        return false;
        // return this.$message.warning(`${data.productName} 的类型标识错误`)
      };
      const parts = this.getParts(L.latLng(lat, lng), radius);
      const polygon = L.polygon(parts, { color: 'red' });
      this.polygons.push(parts)
      const geometryParam = new L.supermap.GetFeaturesByGeometryParameters({
        datasetNames: ["yzqwlsb:yzqwlsbzcxx"],
        geometry: polygon,
        spatialQueryMode: "INTERSECT",
        attributeFilter: `DEVICE_TYPE="${deviceType}"`, // 产品类型过滤
        returnCountOnlyboolean: true,
      });
      LeafletMap.getFeatureService()
        .getFeaturesByGeometry(geometryParam, (serviceResult) => {
          if (!serviceResult.result) return;
          let circle = this.drawCircle(lat, lng, radius, color, data.productName);
          // 设备总数
          this.setData(data.lotDeviceId,serviceResult.result.totalCount);
          circle.bindCustomPopup(getInfowindow({ ...data, totalCount: serviceResult.result.totalCount }))
          var myIcon = L.divIcon({
            html: `<span style="background:${color};padding: 2px">${serviceResult.result.totalCount}</span>`,
            className: 'my-div-icon',
            iconSize: 30
          });
          var myIcon2 = L.divIcon({
            html: '',
            className: 'my-div-icon2',
            iconSize: 30
          });
          L.marker([lat, lng], { icon: myIcon }).addTo(this.map);
          // 不标点
          // let resultLayer = L.geoJSON(serviceResult.result.features, {
          //   style: {
          //     "color": "#ff7800",
          //     "weight": 5,
          //     "opacity": 0.65
          //   },

          //   onEachFeature: function (feature, layer) {
          //     layer.bindPopup(`所属: ${feature.properties.DEPARTMENT_NAME}`)
          //     layer.setIcon(myIcon2)
          //   }
          // })
          // this.map.addLayer(resultLayer)
        });
    },
    getParts(_center, _radius) {
      var point_new = L.CRS.EPSG3857.project(_center);
      var dx = point_new.x, dy = point_new.y;
      var radius = _radius;
      //点集
      var parts = [];
      //计算圆的边缘所有点
      for (var i = 0; i < 360; i++) {
        var radians = (i + 1) * Math.PI / 180;
        var circlePoint = [Math.cos(radians) * radius + dx, Math.sin(radians) * radius + dy];
        parts[i] = L.CRS.EPSG3857.unproject(L.point(circlePoint));
      }
      return parts
    },
    getColor(index) {
      return getColor(index) || '#fff';
    },
    togglePopup(data, index) {
      const tag = this.getTag(data.latitude, data.longitude, data.productName);
      const target = this.circles.filter(item => item.tag === tag)
      if (target.length > 0) {
        this.currentData = { ...data, color: this.getColor(index) };
        target[0].togglePopup();
        this.queryParams.pageSize = 10;
        this.queryParams.pageNum = 1;
        this.getRepetitionIotDeviceInfo(data);
      }
    },
    getQueryIndex() {
      const { pageNum, pageSize } = this.queryParams;
      return {
        fromIndex: (pageNum - 1) * pageSize,
        toIndex: pageNum * pageSize,
      }
    },
    queryService({ latitude, longitude, radius, deviceType, productName, lotDeviceId }) {
      return new Promise(resolve => {
        if (this.getData(lotDeviceId) === 0) {
          return resolve({
            total: 0,
            data: []
          })
        }
        const polygon = L.polygon(this.getParts(L.latLng([latitude, longitude]), radius));
        const geometryParam = new L.supermap.GetFeaturesByGeometryParameters({
          datasetNames: ["yzqwlsb:yzqwlsbzcxx"],
          geometry: polygon,
          spatialQueryMode: "INTERSECT",
          attributeFilter: `DEVICE_TYPE="${deviceType}"`, // 产品类型过滤
          ...this.getQueryIndex()
        });
        LeafletMap.getFeatureService()
          .getFeaturesByGeometry(geometryParam, (serviceResult) => {
            if (!serviceResult.result) return;
            const data = serviceResult.result.features.features.map(i => ({ PRODUCT_NAME: productName, ...i.properties }))
            resolve({
              data,
              total: serviceResult.result.totalCount
            })
          });
      })
    },
    getRepetitionIotDeviceInfo(data) {
      this.queryService(data).then(res => {
        this.total = res.total;
        this.repetitionIotDeviceInfo = res.data.map(item => {
          const list = JSON.parse(item.ASSETATTRIBUTELIST, '{}')
          return {
            ...item,
            DEVICE_APPLICATION_NAME: list[1].value,
            DEPARTMENT_NAME: list[0].value,
          }
        });
      })
    },
    getData(id) {
      let result = this.dataMap.filter(item => item.id === id)
      if (result.length > 0) {
        return result[0].value
      }
      return 0;
    },
    hasData(id) {
      return this.dataMap.filter(item => item.id === id).length > 0
    },
    setData(id, value) {
      if (!this.hasData(id)) this.dataMap.push({
        id,
        value
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
h3 {
  margin: 40px 0 0;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}

#draw-map {
  height: 600px;
}

.draw-map {
  width: 100%;
  height: 100%;
}

.label {
  line-height: 20px;
  cursor: pointer;
}

.color-icon {
  display: inline-block;
  width: 15px;
  height: 15px;
  margin-right: 5px;
  vertical-align: middle;
}

.model-title {
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid #ebecef;
  border-top: 1px solid #ebecef;
  margin-bottom: 24px;
  margin-top: 24px;
  font-family: "PingFang SC";
  font-style: normal;
  font-weight: 500;
  font-size: 14px;

  img {
    width: 16px;
    height: 16px;
    position: relative;
    right: 5px;
    top: 2px;
  }
}

.jy-box {
  width: 100%;
  height: 100%;
  padding: 20px 0;
  position: relative;
  display: flex;
  // justify-content: space-around;

  .jybox-title {
    font-size: 16px;
    color: #000000;
    margin-bottom: 12px;
  }

  .jybox-left {
    margin-left: 10%;
    min-width: 142px;
    height: 142px;
    text-align: center;

    .chart-box {
      width: 400px;
      height: 200px;
    }
  }

  .jybox-right {
    display: inline-block;
    min-width: calc(100% - 400px);
    height: 142px;

    .jybox-right-title {
      font-size: 16px;
      color: #000000;
      margin-bottom: 24px;
      display: inline-block;
    }
  }
}
</style>
